<?php 
declare (strict_types = 1);
namespace app\api\controller;
use app\common\controller\Api;
use think\facade\Db;
use think\Request;
class Script extends Api
{
    protected $with = ['business','script_screen','script_setting_nd','script_setting_xs','script_class.script_setting','script_role'];
    //用户端-排行榜
    public function ph()
    {
        $this->checkLogin();
        $post = param();
        //门店ID
        if(!isset($post['id']) || !isset($post['type'])) return msgerror('参数缺失');
        $UserIndexIntegralLog_model = app('app\api\model\UserIndexIntegralLog');
        $Bussiness_model = app('app\api\model\Business');
        $pm = 0;
        if($post['type'] == 1){
            //本店
            $data = $UserIndexIntegralLog_model->field('sum(num) as hj,user_index_id')->order('hj desc,id desc')->with(['user_index'])->where('business_id',$post['id'])->group('user_index_id')->select();
            if(!empty($data) && !empty($data->toArray())){
                $data = $data->toArray();
                foreach($data as $k=>$v){
                    if($v['user_index_id'] == $this->userinfo['id']){
                        $pm = $k+1;
                        break;
                    }
                }
            }
        }elseif($post['type'] == 2){
            //本市
            $business_data = $Bussiness_model->where('id',$post['id'])->find()->toArray();
            $business_all = $Bussiness_model->where('city_id',$business_data['city_id'])->select()->toArray();
            $ids = [];
            foreach ($business_all as $v){
                $ids[] = $v['id'];
            }
            $ids = implode(',',$ids);
            $data = $UserIndexIntegralLog_model->field('sum(num) as hj,user_index_id')->order('hj desc,id desc')->with(['user_index'])->where('business_id','in',$ids)->group('user_index_id')->select();
            if(!empty($data) && !empty($data->toArray())){
                $data = $data->toArray();
                foreach($data as $k=>$v){
                    if($v['user_index_id'] == $this->userinfo['id']){
                        $pm = $k+1;
                        break;
                    }
                }
            }
        }else{
            //全国
            $data = $UserIndexIntegralLog_model->field('sum(num) as hj,user_index_id')->order('hj desc,id desc')->with(['user_index'])->group('user_index_id')->select();
            if(!empty($data) && !empty($data->toArray())){
                $data = $data->toArray();
                foreach($data as $k=>$v){
                    if($v['user_index_id'] == $this->userinfo['id']){
                        $pm = $k+1;
                        break;
                    }
                }
            }
        }
        $arr = [];
        $arr['user_pm'] = $pm;
        $arr['data'] = $data;
        return datasuccess($arr);
    }
//测试数据用
    public function aaa()
    {
        if (!input('post.id')) {
            return msgerror('缺少参数id');
        }

        $this->where[] = ['id', '=', input('post.id')];
        $list = $this->model->with($this->with)->where($this->where)->find()->toArray();
        //添加流量记录
        $ScriptLlLog_model = app('app\api\model\ScriptLlLog');
        $ScriptLlLog_model->save([
            'business_id'=>$list['business_id'],
            'script_id'=>input('post.id')
        ]);
        $list['sc_status'] = 2;
        //用户端-如果有用户登录的情况下，判断当前用户是否有收藏该剧本
        //1=有，2=无
        if(input('user')){
            $this->checkLogin();
            $Collection_model = app('app\api\model\Collection');
            $colleaction_data = $Collection_model->where([
                ['user_index_id','=',$this->userinfo['id']],
                ['script_id','=',input('id')]
            ])->find();
            if(!empty($colleaction_data) && !empty($colleaction_data->toArray())){
                $list['sc_status'] = 1;
            }
        }
        // $list['images'] = explode(',',$list['images']);
        // foreach ($list['images'] as $kk=>$vv)
        // {
        //     $list['images'][$kk] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $vv;
        // }
        // foreach ($list['script_role'] as $kk=>$vv){
        //     if(!empty($vv['image'])){
        //         $list['script_role'][$kk]['image'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $vv['image'];
        //     }
        // }
        // urladd($list);
        
        
        new_urladd($list);
        return datasuccess($list);
    }
    //用户端-详情接口
    public function view()
    {
        if (!input('post.id')) {
            return msgerror('缺少参数id');
        }

        $this->where[] = ['id', '=', input('post.id')];
        $list = $this->model->with($this->with)->where($this->where)->find()->toArray();
        //添加流量记录
        $ScriptLlLog_model = app('app\api\model\ScriptLlLog');
        $ScriptLlLog_model->save([
            'business_id'=>$list['business_id'],
            'script_id'=>input('post.id')
        ]);
        $list['sc_status'] = 2;
        //用户端-如果有用户登录的情况下，判断当前用户是否有收藏该剧本
        //1=有，2=无
        if(input('user')){
            $this->checkLogin();
            $Collection_model = app('app\api\model\Collection');
            $colleaction_data = $Collection_model->where([
                ['user_index_id','=',$this->userinfo['id']],
                ['script_id','=',input('id')]
            ])->find();
            if(!empty($colleaction_data) && !empty($colleaction_data->toArray())){
                $list['sc_status'] = 1;
            }
        }
        $list['images'] = explode(',',$list['images']);
        foreach ($list['images'] as $kk=>$vv)
        {
            $list['images'][$kk] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $vv;
        }
        foreach ($list['script_role'] as $kk=>$vv){
            if(!empty($vv['image'])){
                $list['script_role'][$kk]['image'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $vv['image'];
            }
        }
        urladd($list);
        
        
        // new_urladd($list);
        return datasuccess($list);
    }
    //用户端-首页-热门剧本
    public function rm_index()
    {
        $post = param();
        if(!isset($post['id'])) return msgerror('参数缺失');
        $limit = $post['limit'] ?? 5;
        $data = $this->model->where([
            ['business_id','=',$post['id']],
            ['status','=',1]
        ])->order('booking desc,id desc')->limit(0,$limit)->select();
        return datasuccess($data);
    }
    //用户端-首页-搜索
    public function ss()
    {
        $post = param();
        if(!isset($post['id']) || !isset($post['name'])) return msgerror('参数缺失');
        $limit = $post['limit'] ?? 20;
        $data = $this->model->where([
            ['business_id','=',$post['id']],
            ['name','like','%'.$post['name'].'%'],
            ['status','=',1]
        ])->with($this->with)->paginate($limit);
        return datasuccess($data);
    }
    //用户端-剧本列表
    public function user_index()
    {
        $post = param();
        if(!isset($post['id'])) return msgerror('参数缺失');
        if(isset($post['name'])){
            $this->where[] = ['business_id','=',$post['id']];
            $this->where[] = ['name','like','%'.$post['name'].'%'];
            $list = $this->model->with($this->with)->order('id desc')->where($this->where)->paginate($this->limit);
            if (!empty($list)) {
                $list = $list->toArray();
                urladd($list);
            }
            return datasuccess($list);
        }
        if(isset($post['sx'])){
            $ScriptScreen_model = app('app\api\model\ScriptScreen');
            //查出当前门店下所有剧本ID
            $data = $this->model->where('business_id','=',$post['id'])->select();
            if(!empty($data) && !empty($data->toArray())){
                $data = $data->toArray();
            }else{
                return datasuccess([]);
            }
            $script_ids = [];
            foreach ($data as $k=>$v){
                $script_ids[] = $v['id'];
            }
            $script_ids = implode(',',$script_ids);
            $where = [
                ['script_id','in',$script_ids],
                ['screen_id','in',(string)$post['sx']]
            ];
            //根据所有剧本ID和筛选ID查出符合记录的剧本ID数据
            $list = $ScriptScreen_model->where($where)->order('id desc')->select();
            if (!empty($list)) {
                $list = $list->toArray();
            }else{
                return datasuccess([]);
            }
            $ids = [];
            foreach ($list as $v){
                $ids[] = $v['script_id'];
            }
            $ids = array_unique($ids);
            $ids = explode(',',$ids);
            $where = [];
            $where[] = ['id','in',$ids];
            $where[] = ['status','=',1];
            //根据数据ID数据重新查询符合排序顺序的分页数据
            $list = $this->model->with($this->with)->order('id desc')->where($where)->paginate($this->limit);
            if (!empty($list)) {
                $list = $list->toArray();
                urladd($list);
            }
            return datasuccess($list);
        }
        $this->where[] = ['business_id','=',$post['id']];
        $list = $this->model->with($this->with)->order('id desc')->where($this->where)->paginate($this->limit);
        if (!empty($list)) {
            $list = $list->toArray();
            urladd($list);
        }
        return datasuccess($list);
    }
    //商户端-我的剧本-列表接口
    public function index()
    {
        $this->businessCheckLogin();
        if (input('post.limit')) {
            $this->limit = input('post.limit');
        }
        $post = array_filter(input('post.'));
        $order = $post['order'] ?? 'status asc,id desc';
        //发送了筛选数据
        if(isset($post['sx'])){
            $ScriptScreen_model = app('app\api\model\ScriptScreen');
            //查出当前门店下所有剧本ID
            $data = $this->model->where('business_id','=',$this->businessinfo['id'])->select();
            if(!empty($data) && !empty($data->toArray())){
                $data = $data->toArray();
            }else{
                return datasuccess([]);
            }
            $script_ids = [];
            foreach ($data as $k=>$v){
                $script_ids[] = $v['id'];
            }
            $script_ids = implode(',',$script_ids);
            $post['sx'] = explode(',',$post['sx']);
            $post['sx'] = array_filter($post['sx']);
            $post['sx'] = implode(',',$post['sx']);
            $where = [
                ['script_id','in',$script_ids],
                ['screen_id','in',(string)$post['sx']]
            ];
            //根据所有剧本ID和筛选ID查出符合记录的剧本ID数据
            $order = 'id desc';
            $list = $ScriptScreen_model->where($where)->order($order)->select();
            if (!empty($list)) {
                $list = $list->toArray();
            }else{
                return datasuccess([]);
            }
            $ids = [];
            foreach ($list as $v){
                $ids[] = $v['script_id'];
            }
            $ids = array_unique($ids);
            $ids = implode(',',$ids);
            $where = [];
            $where[] = ['id','in',$ids];
            
            
            $list = $this->model->where('id','in',$ids)->with('script_screen')->select()->toArray();
            foreach ($list as $k=>$v){
                $num = count(explode(',',$post['sx']));
                $mz = 0;
                foreach ($v['script_screen'] as $kk=>$vv){
                    foreach (explode(',',$post['sx']) as $kkk=>$vvv){
                        if($vv['screen_id'] == $vvv){
                            $mz++;
                        }
                    }
                }
                if($mz < $num){
                    unset($list[$k]);
                }
            }
            if(empty($list)){
               return datasuccess();  
            }else{
                $ids = [];
                foreach ($list as $v){
                    $ids[] = $v['id'];
                }
                $ids = implode(',',$ids);
                $where = [
                    ['id','in',$ids]    
                ];
            }
            
            
            //根据数据ID数据重新查询符合排序顺序的分页数据
            $list = $this->model->with($this->with)->order($order)->where($where)->paginate($this->limit);
            if (!empty($list)) {
                $list = $list->toArray();
                foreach($list['data'] as $k=>$v)
                {
                    $list['data'][$k]['images'] = explode(',',$v['images']);
                    foreach ($list['data'][$k]['images'] as $kk=>$vv)
                    {
                        $list['data'][$k]['images'][$kk] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $vv;
                    }
                    foreach ($v['script_role'] as $kk=>$vv){
                        if(!empty($vv['image'])){
                            $list['data'][$k]['script_role'][$kk]['image'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $vv['image'];
                        }
                    }
                    
                }
                urladd($list);
            }
            return datasuccess($list);
        }
        $this->where[] = ['business_id','=',$this->businessinfo['id']];
        $list = $this->model->with($this->with)->order($order)->where($this->where)->paginate($this->limit);
        if (!empty($list)) {
            $list = $list->toArray();
            foreach($list['data'] as $k=>$v)
            {
                $list['data'][$k]['images'] = explode(',',$v['images']);
                foreach ($list['data'][$k]['images'] as $kk=>$vv)
                {
                    $list['data'][$k]['images'][$kk] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $vv;
                }
                foreach ($v['script_role'] as $kk=>$vv){
                    if(!empty($vv['image'])){
                        $list['data'][$k]['script_role'][$kk]['image'] = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $vv['image'];
                    }
                }
                
            }
            urladd($list);
        }
        return datasuccess($list);
    }
    //商户端-平台剧本列表
    public function pt_index()
    {
        $where = [];
        if(isset($post['sx'])){
            $ScriptScreen_model = app('app\api\model\ScriptScreen');
            //查出当前门店下所有剧本ID
            $data = $this->model->where('business_id','=',$this->businessinfo['id'])->select();
            if(!empty($data) && !empty($data->toArray())){
                $data = $data->toArray();
            }else{
                return datasuccess([]);
            }
            $script_ids = [];
            foreach ($data as $k=>$v){
                $script_ids[] = $v['id'];
            }
            $script_ids = implode(',',$script_ids);
            $where = [
                ['script_id','in',$script_ids],
                ['screen_id','in',(string)$post['sx']]
            ];
            //根据所有剧本ID和筛选ID查出符合记录的剧本ID数据
            $order = 'id desc';
            $list = $ScriptScreen_model->where($where)->order($order)->select();
            if (!empty($list)) {
                $list = $list->toArray();
            }else{
                return datasuccess([]);
            }
            $ids = [];
            foreach ($list as $v){
                $ids[] = $v['script_id'];
            }
            $ids = array_unique($ids);
            $ids = explode(',',$ids);
            $where = [];
            $where[] = ['id','in',$ids];
            $where[] = ['type','=',1];
            if(input('name')){
                $where[] = ['name','like','%'.input('name').'%'];
            }
            //根据数据ID数据重新查询符合排序顺序的分页数据
            $list = $this->model->with($this->with)->order($order)->where($where)->paginate($this->limit);
            if (!empty($list)) {
                $list = $list->toArray();
                urladd($list);
            }
            return datasuccess($list);
        }
        if(input('name')){
            $where[] = ['name','like','%'.input('name').'%'];
        }
        $where[] = ['type','=',1];
        $data = $this->model->where($where)->with($this->with)->select();
        if(!empty($data) && !empty($data->toArray()))
        {
            $data = $data->toArray();
            urladd($data);
        }
        return datasuccess($data);
    }
    //添加自定义剧本
    public function add()
    {
        $this->businessCheckLogin();
        $post = param();
        if(!empty($post)){
            if(!isset($post['name']) || !isset($post['sex_m']) ||
                !isset($post['sex_f']) || !isset($post['script_setting_nd_id']) ||
                !isset($post['price']) || !isset($post['script_setting_xs_id']) ||
                !isset($post['time']) || !isset($post['class_ids']) ||
                    !isset($post['image']) || !isset($post['images']) ||
                !isset($post['content']) || !isset($post['role_ids']) ||
                !isset($post['sx_ids'])){
                return msgerror('参数缺失');
            }
            $class_ids = $post['class_ids'];
            $role_ids = $post['role_ids'];
            $xs_ids = $post['sx_ids'];
            $post['type'] = 2;
            unset($post['sx_ids']);
            unset($post['class_ids']);
            unset($post['role_ids']);
            $this->model->save($post);
            $id = $this->model->id;
            //绑定选中的角色ID到剧本中
            if(!empty($role_ids)){
                $role_ids = explode(',',$role_ids);
                $ScriptRole_model = app('app\admin\model\ScriptRole');
                //绑定添加的角色到剧本上
                foreach($role_ids as $k=>$v)
                {
                    $ScriptRole_model::update(['id'=>$v,'script_id'=>$id]);
                }
            }
            //添加类型数据到中间表中
            if(!empty($class_ids)){
                $class_ids = explode(',',$class_ids);
                $ScriptClass_model = app('app\admin\model\ScriptClass');
                $arr = [];
                //绑定添加的角色到剧本上
                foreach($class_ids as $k=>$v)
                {
                    $arr[] = ['script_id'=>$id,'script_setting_id'=>$v];
                }
                $ScriptClass_model->saveAll($arr);
            }
            //添加筛选数据到中间表中
            if(!empty($xs_ids)){
                $xs_ids = explode(',',$xs_ids);
                $ScriptScreen_model = app('app\admin\model\ScriptScreen');
                $arr = [];
                //绑定添加的角色到剧本上
                foreach($xs_ids as $k=>$v)
                {
                    $arr[] = ['script_id'=>$id,'screen_id'=>$v];
                }
                $ScriptScreen_model->saveAll($arr);
            }
            return datasuccess([],'添加成功');
        }else{
            return msgerror('数据不能为空');
        }

    }
    //选择平台剧本添加
    public function pt_add()
    {
        $this->businessCheckLogin();
        $post = param();
        if(!isset($post['ids'])) return msgerror('参数缺失');
        $data = $this->model->where('id','in',$post['ids'])->with($this->with)->select()->toArray();
        //组装剧本数据-添加
        foreach ($data as $v)
        {
            unset($v['booking']);
            unset($v['id']);
            unset($v['browse']);
            $v['business_id'] = $this->businessinfo['id'];
            $v['type'] = 2;
            //添加剧本数据
            $res = $v;
            unset($res['business']);
            unset($res['script_screen']);
            unset($res['script_setting_nd']);
            unset($res['script_setting_xs']);
            unset($res['script_class']);
            unset($res['script_role']);
            $id = Db::name('script')->insertGetId($res);
            //根据新增的剧本ID添加对应的类型中间表数据
            $arr = [];
            foreach ($v['script_class'] as $vv){
                $arr[] = [
                    'script_id'=>$id,
                    'script_setting_id'=>$vv['script_setting_id']
                ];
            }
            if(!empty($arr)){
                Db::name('script_class')->insertAll($arr);
            }
            //根据新增的剧本ID添加对应的筛选中间表数据
            $arr = [];
            foreach ($v['script_screen'] as $vv){
                $arr[] = [
                    'script_id'=>$id,
                    'screen_id'=>$vv['screen_id']
                ];
            }
            if(!empty($arr)){
                Db::name('script_screen')->insertAll($arr);
            }
            //根据新增的剧本ID添加对应的任务数据
            $arr = [];
            foreach ($v['script_role'] as $vv){
                $arr[] = [
                    'script_id'=>$id,
                    'name'=>$vv['name'],
                    'image'=>$vv['image'],
                    'content'=>$vv['content']
                ];
            }
            if(!empty($arr)){
                Db::name('script_role')->insertAll($arr);
            }
        }
        return datasuccess([],'添加成功');
    }
    //商户端-编辑剧本
    public function upload()
    {
        $this->businessCheckLogin();
        $post = input('post.');
        if($post){
            if(!isset($post['id']) || empty($post['id'])) return msgerror('参数缺失');
            //检测到类型ID
            if(isset($post['class_ids'])){
                Db::name('script_class')->where('script_id','=',$post['id'])->delete();
                if(!empty($post['class_ids'])){
                    $class_ids = explode(',',$post['class_ids']);
                    $ScriptClass_model = app('app\admin\model\ScriptClass');
                    $arr = [];
                    //绑定添加的角色到剧本上
                    foreach($class_ids as $k=>$v)
                    {
                        $arr[] = ['script_id'=>$post['id'],'script_setting_id'=>$v];
                    }
                    $ScriptClass_model->saveAll($arr);
                }
            }
            unset($post['class_ids']);
            //检测到类型角色ID
            if(isset($post['role_ids'])){
                $ScriptRole_model = app('app\admin\model\ScriptRole');
                if(!empty($post['role_ids'])){
                    $role_ids = explode(',',$post['role_ids']);
                    $ScriptRole_data = $ScriptRole_model->where('script_id',$post['id'])->select();
                    if(!empty($ScriptRole_data) && !empty($ScriptRole_data->toArray())){
                        $ScriptRole_data = $ScriptRole_data->toArray();
                        $ids = [];
                        foreach ($ScriptRole_data as $k=>$v)
                        {
                            $ids[] = $v['id'];
                        }
                        $c_ids = array_diff($ids,$role_ids);
                        if(!empty($c_ids)){
                            //不为空表示有需要删除的角色ID数据
                            $c_ids = implode(',',$c_ids);
                            $ScriptRole_model->where('id','in',$c_ids)->select()->delete();
                        }
                    }
                    //绑定添加的角色到剧本上
                    foreach($role_ids as $k=>$v)
                    {
                        $ScriptRole_model::update(['id'=>$v,'script_id'=>$post['id']]);
                    }
                }else{
                    $ScriptRole_model->where('script_id','=',$post['id'])->select()->delete();
                }
            }else{
                $ScriptRole_model->where('script_id','=',$post['id'])->select()->delete();
            }
            unset($post['role_ids']);
            //添加筛选数据到中间表中
            if(isset($post['sx_ids'])){
                $ScriptScreen_model = app('app\admin\model\ScriptScreen');
                $ScriptScreen_model->where('script_id','=',$post['id'])->select()->delete();
                if(!empty($post['sx_ids'])){
                    $xs_ids = explode(',',$post['sx_ids']);
                    $arr = [];
                    //绑定添加的角色到剧本上
                    foreach($xs_ids as $k=>$v)
                    {
                        $arr[] = ['script_id'=>$post['id'],'screen_id'=>$v];
                    }
                    $ScriptScreen_model->saveAll($arr);
                }
            }
            unset($post['sx_ids']);
            $this->model::update($post);
            return datasuccess([],'修改成功');
        }else{
            return msgerror('数据为空');
        }
    }
    public function cz()
    {
        $this->businessCheckLogin();
        $post = param();
        if(!empty($post['id']));

        $data = $this->model->where([['id','=',$post['id']],['business_id','=',$this->businessinfo['id']]])->find();
        if(!empty($data) && !empty($data->toArray()))
        {
            $data = $data->toArray();
            if($data['status'] == 1){
                $this->model::update(['id'=>$data['id'],'status'=>2]);
            }else{
                $this->model::update(['id'=>$data['id'],'status'=>1]);
            }
        }else{
            return msgerror('数据不存在，操作失败');
        }
        return datasuccess([],'操作成功');
    }
}